// pages/business/health-score/health-score.js
Page({

  // 获取模拟的积分来源数据
  getMockPointsSources() {
    return [
      { name: '购物获得', value: 856, percentage: 68, icon: 'shopping-cart-o' },
      { name: '牙齿检查', value: 240, percentage: 19, icon: 'medkit-o' },
      { name: '健康监测', value: 165, percentage: 13, icon: 'line-chart-o' }
    ];
  },

  // 获取模拟的积分历史数据
  getMockPointsHistory() {
    return [
      { id: 1, type: '获得', source: '商城购物', points: '+120', date: '2024-05-20', desc: '购买电动牙刷' },
      { id: 2, type: '获得', source: '牙齿检查', points: '+80', date: '2024-05-15', desc: '定期牙齿检查' },
      { id: 3, type: '使用', source: '积分兑换', points: '-200', date: '2024-05-10', desc: '兑换50元优惠券' },
      { id: 4, type: '获得', source: '健康监测', points: '+30', date: '2024-05-08', desc: '完成刷牙打卡' },
      { id: 5, type: '获得', source: '商城购物', points: '+156', date: '2024-05-01', desc: '购买牙膏套装' }
    ];
  },

  // 获取模拟的优惠券数据
  getMockCoupons() {
    return [
      { id: 1, name: '满100减50元优惠券', value: 50, minSpend: 100, points: 200, expireDate: '2024-06-30', remaining: 50 },
      { id: 2, name: '满50减20元优惠券', value: 20, minSpend: 50, points: 100, expireDate: '2024-06-30', remaining: 100 },
      { id: 3, name: '满30减10元优惠券', value: 10, minSpend: 30, points: 50, expireDate: '2024-06-30', remaining: 200 }
    ];
  },

  // 获取模拟的商品数据
  getMockProducts() {
    return [
      { id: 1, name: '专业护理牙膏', image: '/assets/images/my/avatar.jpg', points: 150, stock: 100, desc: '含氟配方，有效防蛀' },
      { id: 2, name: '儿童牙刷套装', image: '/assets/images/my/avatar.jpg', points: 120, stock: 50, desc: '软毛设计，温和清洁' },
      { id: 3, name: '口腔清新喷雾', image: '/assets/images/my/avatar.jpg', points: 80, stock: 80, desc: '持久清新，方便携带' },
      { id: 4, name: '牙线棒（100支）', image: '/assets/images/my/avatar.jpg', points: 50, stock: 200, desc: '超细滑线，深入清洁' }
    ];
  },

  // 获取模拟的会员等级信息
  getMockLevelInfo() {
    return {
      currentLevel: '白银会员',
      nextLevel: '黄金会员',
      progress: 65,
      nextLevelPoints: 2000
    };
  },

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: true,
    totalPoints: 1258,
    animatedPoints: 0,
    filteredHistory: [],
    currentFilter: 'all',
    pointsSources: [],
    pointsHistory: [],
    coupons: [],
    products: [],
    levelInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 模拟数据加载延迟
    setTimeout(() => {
      // 使用封装的函数获取数据
      const pointsHistory = this.getMockPointsHistory();
      const pointsSources = this.getMockPointsSources();
      const coupons = this.getMockCoupons();
      const products = this.getMockProducts();
      const levelInfo = this.getMockLevelInfo();
      
      // 更新页面数据
      this.setData({
        isLoading: false,
        pointsHistory: pointsHistory,
        pointsSources: pointsSources,
        coupons: coupons,
        products: products,
        levelInfo: levelInfo,
        filteredHistory: pointsHistory // 初始化过滤后的历史记录
      });
      
      this.animatePointsDisplay();
      this.initProgressAnimation();
    }, 800);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 刷新数据
    this.fetchUserPointsData();
  },

  // 获取用户积分数据
  fetchUserPointsData() {
    return new Promise((resolve) => {
      // 模拟从服务器获取数据
      // 实际应用中应该调用API获取真实数据
      
      // 计算各来源积分的百分比
      const sources = this.data.pointsSources;
      const total = sources.reduce((sum, item) => sum + item.value, 0);
      const sourcesWithPercentage = sources.map(item => ({
        ...item,
        percentage: Math.round((item.value / total) * 100)
      }));
      
      this.setData({
        pointsSources: sourcesWithPercentage
      });
      
      // 模拟延迟加载效果
      setTimeout(() => {
        this.animatePointsDisplay();
        resolve();
      }, 300);
    });
  },
  
  // 积分数字动画效果
  animatePointsDisplay() {
    const targetPoints = this.data.totalPoints;
    let currentPoints = 0;
    const duration = 1500; // 动画持续时间（毫秒）
    const steps = 30; // 动画步数
    const stepPoints = Math.floor(targetPoints / steps);
    
    let step = 0;
    const timer = setInterval(() => {
      step++;
      currentPoints += stepPoints;
      
      // 最后一步确保显示准确值
      if (step >= steps) {
        currentPoints = targetPoints;
        clearInterval(timer);
      }
      
      this.setData({
        animatedPoints: currentPoints
      });
    }, duration / steps);
  },

  // 切换标签页
  onTabChange(event) {
    try {
      // 支持不同参数格式
      const index = event.currentTarget ? parseInt(event.currentTarget.dataset.index) : (event.detail ? event.detail.index : 0);
      
      this.setData({
        activeTab: index
      });
      
      // 标签切换时的动画效果 (可选)
      const query = wx.createSelectorQuery();
      query.selectAll('.tab-item').boundingClientRect();
      query.exec((res) => {
        if (res && res[0] && res[0].length > 0) {
          // 可以在这里添加更多动画效果
        }
      });
    } catch (error) {
      console.error('切换标签失败:', error);
    }
  },
  
  // 过滤积分记录
  filterHistory(event) {
    try {
      const type = event.currentTarget.dataset.type;
      const allHistory = this.data.pointsHistory || [];
      let filtered;
      
      if (type === 'all') {
        filtered = allHistory;
      } else if (type) {
        filtered = allHistory.filter(item => item && item.type === type);
      } else {
        filtered = allHistory;
      }
      
      this.setData({
        filteredHistory: filtered,
        currentFilter: type || 'all' // 更新当前筛选状态
      });
      
      // 如果筛选结果为空，显示空状态提示
      if (filtered.length === 0) {
        wx.showToast({
          title: '暂无相关记录',
          icon: 'none',
          duration: 1000
        });
      }
    } catch (error) {
      console.error('筛选历史记录失败:', error);
      // 出错时重置为全部记录
      this.setData({
        filteredHistory: this.data.pointsHistory || [],
        currentFilter: 'all'
      });
    }
  },
  
  // 按时间排序积分记录
  sortHistory(event) {
    try {
      const order = event.currentTarget.dataset.order || 'desc';
      const history = [...(this.data.filteredHistory || this.data.pointsHistory || [])];
      history.sort((a, b) => {
        try {
          const dateA = a && a.date ? new Date(a.date).getTime() : 0;
          const dateB = b && b.date ? new Date(b.date).getTime() : 0;
          
          if (order === 'desc') {
            return dateB - dateA;
          } else {
            return dateA - dateB;
          }
        } catch (e) {
          return 0;
        }
      });
      
      this.setData({
        filteredHistory: history
      });
      
      wx.showToast({
        title: '已按时间排序',
        icon: 'success',
        duration: 1000
      });
    } catch (error) {
      console.error('排序历史记录失败:', error);
    }
  },
  
  // 查看积分详情
  viewPointsDetail(e) {
    try {
      const source = e.currentTarget.dataset.source;
      if (!source) {
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
        return;
      }
      
      const sourceData = this.data.pointsSources.find(item => item.name === source);
      if (sourceData) {
        wx.showModal({
          title: source,
          content: `获得方式：${source}\n当前积分：${sourceData.value}分`,
          showCancel: false,
          fail: (err) => {
            console.error('弹窗失败:', err);
          }
        });
      } else {
        wx.showModal({
          title: source,
          content: `查看${source}的详细说明`,
          showCancel: false,
          fail: (err) => {
            console.error('弹窗失败:', err);
          }
        });
      }
    } catch (error) {
      console.error('查看积分详情失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  },

  // 兑换优惠券
  exchangeCoupon(e) {
    try {
      const couponId = e.currentTarget.dataset.id;
      if (!couponId) {
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
        return;
      }
      
      const coupon = this.data.coupons.find(c => c && c.id === couponId);
      if (!coupon) {
        wx.showToast({
          title: '未找到优惠券',
          icon: 'none'
        });
        return;
      }
      
      // 检查积分是否足够
      if (this.data.totalPoints < coupon.points) {
        wx.showToast({
          title: '积分不足',
          icon: 'none',
          duration: 2000
        });
        // 可以添加引导用户获取更多积分的提示
        return;
      }
      
      // 检查库存是否充足
      if (coupon.remaining <= 0) {
        wx.showToast({
          title: '优惠券已兑完',
          icon: 'none'
        });
        return;
      }
      
      wx.showModal({
        title: '确认兑换',
        content: `确认使用${coupon.points}积分兑换「${coupon.name}」吗？`,
        success: (res) => {
          if (res.confirm) {
            // 模拟兑换成功
            this.simulateExchange(coupon);
          }
        },
        fail: (err) => {
          console.error('弹窗失败:', err);
        }
      });
    } catch (error) {
      console.error('兑换优惠券失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  },

  // 兑换商品
  exchangeProduct(e) {
    try {
      const productId = e.currentTarget.dataset.id;
      if (!productId) {
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
        return;
      }
      
      const product = this.data.products.find(p => p && p.id === productId);
      if (!product) {
        wx.showToast({
          title: '未找到商品',
          icon: 'none'
        });
        return;
      }
      
      // 检查积分是否足够
      if (this.data.totalPoints < product.points) {
        wx.showToast({
          title: '积分不足',
          icon: 'none',
          duration: 2000
        });
        // 可以添加引导用户获取更多积分的提示
        return;
      }
      
      // 检查库存是否充足
      if (product.stock <= 0) {
        wx.showToast({
          title: '商品已兑完',
          icon: 'none'
        });
        return;
      }
      
      wx.showModal({
        title: '确认兑换',
        content: `确认使用${product.points}积分兑换「${product.name}」吗？`,
        success: (res) => {
          if (res.confirm) {
            // 模拟兑换成功
            this.simulateExchange(product, 'product');
          }
        },
        fail: (err) => {
          console.error('弹窗失败:', err);
        }
      });
    } catch (error) {
      console.error('兑换商品失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  },
  
  // 模拟兑换成功过程
  simulateExchange(item, type = 'coupon') {
    wx.showLoading({
      title: '兑换中...',
    });
    
    // 模拟网络请求延迟
    setTimeout(() => {
      wx.hideLoading();
      
      // 更新积分和库存
      const newTotalPoints = this.data.totalPoints - item.points;
      const updatedHistory = [
        {
          id: Date.now(),
          type: '使用',
          source: '积分兑换',
          points: `-${item.points}`,
          date: new Date().toISOString().split('T')[0],
          desc: type === 'coupon' ? `兑换${item.name}` : `兑换${item.name}`
        },
        ...(this.data.pointsHistory || [])
      ];
      
      let updatedCoupons = [...this.data.coupons];
      let updatedProducts = [...this.data.products];
      
      if (type === 'coupon') {
        updatedCoupons = updatedCoupons.map(c => 
          c.id === item.id ? { ...c, remaining: c.remaining - 1 } : c
        );
      } else {
        updatedProducts = updatedProducts.map(p => 
          p.id === item.id ? { ...p, stock: p.stock - 1 } : p
        );
      }
      
      this.setData({
        totalPoints: newTotalPoints,
        animatedPoints: newTotalPoints,
        pointsHistory: updatedHistory,
        filteredHistory: updatedHistory,
        coupons: updatedCoupons,
        products: updatedProducts
      });
      
      // 显示兑换成功动画
      this.showExchangeSuccess();
    }, 1000);
  },
  
  // 显示兑换成功动画
  showExchangeSuccess() {
    try {
      // 创建一个临时的成功提示元素
      wx.showToast({
        title: '兑换成功',
        icon: 'success',
        duration: 2000
      });
      
      // 移除震动反馈，避免屏幕抖动
      // 可以在这里添加更多的动画效果
    } catch (error) {
      console.error('显示成功提示失败:', error);
    }
  },
  
  // 初始化进度条动画
  initProgressAnimation() {
    // 直接使用data中的百分比值更新UI
    // 积分来源进度条
    if (this.data.pointsSources && this.data.pointsSources.length > 0) {
      this.data.pointsSources.forEach((source, index) => {
        if (source && source.percentage !== undefined) {
          this.setData({
            [`pointsSources[${index}].displayPercentage`]: `${source.percentage}%`
          });
        }
      });
    }
    
    // 会员等级进度条
    if (this.data.levelInfo && this.data.levelInfo.progress !== undefined) {
      this.setData({
        'levelInfo.displayProgress': `${this.data.levelInfo.progress}%`
      });
    }
  },

  // 查看积分规则
  viewPointsRules() {
    wx.showModal({
      title: '积分规则',
      content: '1. 购物获得：消费金额×0.1的积分\n2. 牙齿检查：每次检查获得50-100积分\n3. 健康监测：完成刷牙打卡获得10-30积分\n4. 积分可用于兑换优惠券或实物商品',
      showCancel: false
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.fetchUserPointsData();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的健康积分',
      path: '/pages/business/health-score/health-score'
    };
  }
})